package com.cloud.message.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.annex.AnnexUrlService;
import com.cloud.common.domain.Result;
import com.cloud.domain.LoginUser;
import com.cloud.domain.UserProject;
import com.cloud.entity.SysNotice;
import com.cloud.entity.SysNoticeUser;
import com.cloud.entity.SysRole;
import com.cloud.entity.vo.NoticeParam;
import com.cloud.enums.NoticeType;
import com.cloud.enums.ReadStatus;
import com.cloud.common.enums.ReturnStatus;
import com.cloud.message.entity.SysNoticeDept;
import com.cloud.message.entity.SysNoticeRole;
import com.cloud.message.entity.vo.NoticeCount;
import com.cloud.message.entity.vo.NoticeUserDao;
import com.cloud.message.entity.vo.SysNoticeParam;
import com.cloud.message.mapper.SysNoticeDeptMapper;
import com.cloud.message.mapper.SysNoticeMapper;
import com.cloud.message.mapper.SysNoticeRoleMapper;
import com.cloud.message.mapper.SysNoticeUserMapper;
import com.cloud.message.service.IMessageService;
import com.cloud.message.service.ISysNoticeService;
import com.cloud.scope.DataScope;
import com.cloud.user_info.service.ISysRoleService;
import com.cloud.utils.DateTimeUtils;
import com.cloud.utils.SecurityUtils;
import com.cloud.utils.StringUtils;
import com.cloud.utils.ToolUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 公告 服务层实现
 *
 * @author yzj
 */
@Service
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeMapper, SysNotice> implements ISysNoticeService {

    @Resource
    private SysNoticeMapper noticeMapper;

    @Resource
    private SysNoticeUserMapper noticeUserMapper;

    @Resource
    private SysNoticeRoleMapper noticeRoleMapper;

    @Resource
    private SysNoticeDeptMapper noticeDeptMapper;

    @Resource
    private AnnexUrlService annexUrlService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IMessageService messageService;

    /**
     * 查询公告列表
     *
     * @param notice 公告信息
     * @return 公告集合
     */
    @Override
    @DataScope(deptAlias = "sn", userAlias = "u")
    public List<SysNotice> selectNoticeList(SysNotice notice) {
        return noticeMapper.selectNoticeList(notice);
    }

    /**
     * 查询公告信息
     *
     * @param noticeId 公告ID
     * @return 公告信息
     */
    @Override
    public SysNotice selectNoticeById(Long noticeId) {
        // 获取系统消息详情
        SysNotice sysNotice = noticeMapper.selectById(noticeId);
        if (StringUtils.isNotNull(sysNotice)) {
            // 转换图片,附件访问路径
            sysNotice.setImageUrl(annexUrlService.getImageTurnPath(sysNotice.getImageUrl()));
            sysNotice.setVideoUrl(annexUrlService.getVideoTurnPath(sysNotice.getVideoUrl()));
            sysNotice.setOtherUrl(annexUrlService.getAnnexTurnPath(sysNotice.getOtherUrl()));
            updateUserNoticeList(SecurityUtils.getUserId(), noticeId);
        }
        return sysNotice;
    }

    /**
     * 新增公告
     *
     * @param notice 公告信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNotice(SysNotice notice) {
        notice.setOuterId(ToolUtils.getUuid());
        notice.setStatus(ReturnStatus.OK.getCode());
        int rows = noticeMapper.insert(notice);
        // 指定用户通知
        if (StringUtils.isNotEmpty(notice.getUserIds())) {
            rows = sendNoticeInfo(notice);
            // 指定角色通知
        } else if (StringUtils.isNotEmpty(notice.getRoleIds())) {
            List<Long> roleIdList = ToolUtils.setIdsToList(notice.getRoleIds());
            List<SysNoticeRole> noticeRoleList = new ArrayList<>();
            for (Long roleId : roleIdList) {
                SysNoticeRole noticeRole = new SysNoticeRole();
                noticeRole.setNoticeId(notice.getNoticeId());
                noticeRole.setRoleId(roleId);
                noticeRoleList.add(noticeRole);
            }
            if (noticeRoleList.size() > 0) {
                rows = noticeRoleMapper.batchNoticeRole(noticeRoleList);
            }
            // 指定部门通知
        } else if (StringUtils.isNotEmpty(notice.getDeptIds())) {
            List<Long> deptIdList = ToolUtils.setIdsToList(notice.getDeptIds());
            List<SysNoticeDept> noticeDeptList = new ArrayList<>();
            for (Long deptId : deptIdList) {
                SysNoticeDept noticeDept = new SysNoticeDept();
                noticeDept.setNoticeId(notice.getNoticeId());
                noticeDept.setDeptId(deptId);
                noticeDeptList.add(noticeDept);
            }
            if (noticeDeptList.size() > 0) {
                rows = noticeDeptMapper.batchNoticeDept(noticeDeptList);
            }
            // TODO 未指定用户,角色,部门通知,默认发送当前部门消息通知
        } else {
            SysNoticeDept noticeDept = new SysNoticeDept();
            noticeDept.setNoticeId(notice.getNoticeId());
            noticeDept.setDeptId(notice.getDeptId());
            noticeDeptMapper.insert(noticeDept);
        }
        return rows;
    }

    /**
     * 修改公告
     *
     * @param notice 公告信息
     * @return 结果
     */
    @Override
    public int updateNotice(SysNotice notice) {
        return noticeMapper.updateById(notice);
    }

    /**
     * 批量删除公告信息
     *
     * @param noticeIds 需要删除的公告ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNoticeByIds(List<Long> noticeIds) {
        // 删除用户组
        noticeUserMapper.deleteUserNoticeByNoticeId(noticeIds);
        // 删除角色组
        noticeRoleMapper.deleteNoticeRoleByNoticeId(noticeIds);
        // 删除部门组
        noticeDeptMapper.deleteNoticeDeptByNoticeId(noticeIds);
        // 删除消息公告信息
        return noticeMapper.deleteBatchIds(noticeIds);
    }

    /**
     * 发送通知信息
     */
    private int sendNoticeInfo(SysNotice notice) {
        int rows = 0;
        NoticeParam noticeParam = new NoticeParam();
        noticeParam.setSysCode(notice.getSysCode());
        noticeParam.setSendType(notice.getSendType());
        noticeParam.setOuterId(notice.getOuterId());
        noticeParam.setNoticeId(notice.getNoticeId());
        noticeParam.setTitle(notice.getNoticeTitle());
        noticeParam.setContent(notice.getNoticeContent());
        noticeParam.setUserIdList(ToolUtils.setIdsToList(notice.getUserIds()));
        // 根据消息类型指定用户发送第三方信息
        List<SysNoticeUser> noticeUserList = messageService.setNoticeUserInfo(noticeParam);
        if (noticeUserList.size() > 0) {
            rows = noticeUserMapper.batchUserNotice(noticeUserList);
        }
        return rows;
    }

    /**
     * 查询用户相关的通信息
     *
     * @param notice
     * @return
     */
    @Override
    public List<NoticeUserDao> getUserNoticeList(SysNotice notice) {
        return noticeMapper.selectUserNoticeList(notice);
    }

    /**
     * 查询用户相关的通知数量
     *
     * @return
     */
    @Override
    public NoticeCount getUserNoticeCount(SysNotice notice) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        notice.setUserId(loginUser.getUser().getUserId());
        // 根据用户ID查询项目角色ID数组
        String roleIds = roleService.selectProjectRoleIds(loginUser.getSysCode(), notice.getUserId());
        if (StringUtils.isNotNull(loginUser.getUser().getDept()) || StringUtils.isNotEmpty(roleIds)) {
            notice.setDeptId(loginUser.getUser().getDeptId());
            notice.setRoleIds(roleIds);
        }
        NoticeCount noticeCount = new NoticeCount();
        // 查询最新通知消息
        notice.setNoticeType(NoticeType.NOTICE.getCode());
        SysNotice noticeInfo = noticeMapper.selectUserNoticeInfo(notice);
        if (StringUtils.isNotNull(noticeInfo)) {
            noticeCount.setNoticeNum(noticeInfo.getNoticeCount());
            noticeCount.setNoticeInfo(noticeInfo);
        } else {
            noticeCount.setNewsNum(0);
        }
        // 查询最新公告消息
        notice.setNoticeType(NoticeType.ANNOUNCEMENT.getCode());
        SysNotice newsNotice = noticeMapper.selectUserNoticeInfo(notice);
        if (StringUtils.isNotNull(newsNotice)) {
            noticeCount.setNewsNum(newsNotice.getNoticeCount());
            noticeCount.setNewsInfo(newsNotice);
        } else {
            noticeCount.setNewsNum(0);
        }
        // 查询最新任务消息
        notice.setNoticeType(NoticeType.TASK_NOTICE.getCode());
        SysNotice taskNotice = noticeMapper.selectUserNoticeInfo(notice);
        if (StringUtils.isNotNull(taskNotice)) {
            noticeCount.setTaskNum(taskNotice.getNoticeCount());
            noticeCount.setTaskInfo(taskNotice);
        } else {
            noticeCount.setTaskNum(0);
        }
        // 查询最新预警信息
        notice.setNoticeType(NoticeType.EARLY_WARNING.getCode());
        SysNotice earlyNotice = noticeMapper.selectUserNoticeInfo(notice);
        if (StringUtils.isNotNull(earlyNotice)) {
            noticeCount.setEarlyNum(earlyNotice.getNoticeCount());
            noticeCount.setEarlyInfo(earlyNotice);
        } else {
            noticeCount.setEarlyNum(0);
        }
        return noticeCount;
    }

    /**
     * 清除我的通知消息
     *
     * @return
     */
    @Override
    public Result cleanUserNotice(SysNotice notice) {
        List<NoticeUserDao> noticeUserList = noticeMapper.selectUserNoticeList(notice);
        if (noticeUserList.size() > 0) {
            for (NoticeUserDao noticeUserDao : noticeUserList) {
                updateUserNoticeList(notice.getUserId(), noticeUserDao.getNoticeId());
            }
        }
        return Result.success("操作成功");
    }

    /**
     * 根据类型查询消息
     */
    @Override
    public Result selectNavNoticeList(SysNoticeParam noticeParam) {
        noticeParam.setBeginTime(DateTimeUtils.getStartDataTime(0));
        noticeParam.setEndTime(DateTimeUtils.getEndDataTime(0));
        return Result.success("查询成功", noticeMapper.selectNavNoticeList(noticeParam));
    }

    /**
     * 更新用户对公告阅读状态
     */
    private int updateUserNoticeList(Long userId, Long noticeId) {
        int rows = 0;
        SysNoticeUser noticeUser = new SysNoticeUser();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        UserProject userProject = loginUser.getUserProject();
        if (StringUtils.isNotNull(userProject)) {
            List<SysRole> roleList = userProject.getRoleList();
            if (roleList.size() > 0) {
                // 要是账户多个角色,设置第一个角色ID信息
                noticeUser.setRoleId(roleList.get(0).getRoleId());
            }
        }
        noticeUser.setDeptId(loginUser.getUser().getDeptId());
        noticeUser.setUserId(userId);
        noticeUser.setNoticeId(noticeId);
        noticeUser.setReadStatus(ReadStatus.HAVE_READ.getCode());
        if (noticeUserMapper.checkUserUnique(noticeId, userId) > 0) {
            rows = noticeUserMapper.updateUserNotice(noticeUser);
        } else {
            // TODO 如果记录不存在则创建用户阅读记录
            rows = noticeUserMapper.insert(noticeUser);
        }
        return rows;
    }

}
